<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket实时听单系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        /* 自定义样式 */
        .order-card {
            transition: all 0.3s ease;
            border-left: 4px solid #007bff;
        }
        .order-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .status-badge {
            font-size: 0.8em;
            padding: 0.25em 0.5em;
        }
        .status-pending { background-color: #ffc107; color: #000; }
        .status-confirmed { background-color: #28a745; color: #fff; }
        .status-paid { background-color: #17a2b8; color: #fff; }
        .status-cancelled { background-color: #dc3545; color: #fff; }
        .status-completed { background-color: #6c757d; color: #fff; }
        
        .payment-status-pending { background-color: #ffc107; color: #000; }
        .payment-status-paid { background-color: #28a745; color: #fff; }
        .payment-status-failed { background-color: #dc3545; color: #fff; }
        
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1050;
            min-width: 300px;
        }
        
        .connection-status {
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 1050;
        }
        
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .order-item {
            border-bottom: 1px solid #eee;
            padding: 10px 0;
        }
        
        .order-item:last-child {
            border-bottom: none;
        }
        
        .real-time-indicator {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        
        .log-container {
            height: 300px;
            overflow-y: auto;
            background-color: #f8f9fa;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-family: monospace;
        }
        .log-entry {
            margin-bottom: 5px;
            padding: 2px 5px;
            border-radius: 3px;
        }
        .log-info { background-color: #d1ecf1; }
        .log-success { background-color: #d4edda; }
        .log-warning { background-color: #fff3cd; }
        .log-error { background-color: #f8d7da; }
        
        .status-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 5px;
        }
        .status-connected { background-color: #28a745; }
        .status-disconnected { background-color: #dc3545; }
        .status-connecting { background-color: #ffc107; }
    </style>
</head>
<body>
    <div class="container-fluid">
        <!-- 连接状态指示器 -->
        <div class="connection-status">
            <div class="alert alert-info" id="connectionStatus">
                <i class="fas fa-circle text-danger"></i> 连接中...
            </div>
        </div>
        
        <!-- 页面标题 -->
        <div class="row mb-4">
            <div class="col-12">
                <h1 class="text-center">
                    <i class="fas fa-headphones text-primary"></i> WebSocket实时听单系统
                    <span class="badge bg-success real-time-indicator">实时</span>
                </h1>
            </div>
        </div>
        
        <!-- 连接控制 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-plug"></i> 连接控制</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <label for="userId" class="form-label">用户ID</label>
                                <input type="text" class="form-control" id="userId" value="test_user_001" placeholder="输入用户ID">
                            </div>
                            <div class="col-md-6">
                                <label for="serverUrl" class="form-label">服务器地址</label>
                                <input type="text" class="form-control" id="serverUrl" value="ws://localhost:8080/ws" placeholder="WebSocket服务器地址">
                            </div>
                        </div>
                        <div class="mt-3">
                            <button class="btn btn-success" onclick="connect()" id="connectBtn">
                                <i class="fas fa-link"></i> 连接
                            </button>
                            <button class="btn btn-danger" onclick="disconnect()" id="disconnectBtn" disabled>
                                <i class="fas fa-unlink"></i> 断开
                            </button>
                            <button class="btn btn-info" onclick="ping()" id="pingBtn" disabled>
                                <i class="fas fa-heartbeat"></i> Ping
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-info-circle"></i> 连接状态</h5>
                    </div>
                    <div class="card-body">
                        <div class="d-flex align-items-center mb-2">
                            <span class="status-indicator status-disconnected" id="statusIndicator"></span>
                            <span id="connectionStatusText">未连接</span>
                        </div>
                        <div class="mb-2">
                            <strong>连接时间:</strong> <span id="connectionTime">-</span>
                        </div>
                        <div class="mb-2">
                            <strong>消息计数:</strong> <span id="messageCount">0</span>
                        </div>
                        <div>
                            <strong>最后消息:</strong> <span id="lastMessage">-</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 统计信息 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card stats-card">
                    <div class="card-body text-center">
                        <h5 class="card-title">总订单数</h5>
                        <h2 id="totalOrders">0</h2>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stats-card">
                    <div class="card-body text-center">
                        <h5 class="card-title">待处理</h5>
                        <h2 id="pendingOrders">0</h2>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stats-card">
                    <div class="card-body text-center">
                        <h5 class="card-title">已确认</h5>
                        <h2 id="confirmedOrders">0</h2>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stats-card">
                    <div class="card-body text-center">
                        <h5 class="card-title">已完成</h5>
                        <h2 id="completedOrders">0</h2>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 筛选和搜索 -->
        <div class="row mb-3">
            <div class="col-md-4">
                <select class="form-select" id="statusFilter">
                    <option value="">所有状态</option>
                    <option value="1">待确认</option>
                    <option value="2">已确认</option>
                    <option value="3">已支付</option>
                    <option value="4">已完成</option>
                    <option value="5">已取消</option>
                </select>
            </div>
            <div class="col-md-4">
                <input type="text" class="form-control" id="searchInput" placeholder="搜索订单号或用户ID">
            </div>
            <div class="col-md-4">
                <button class="btn btn-primary" onclick="refreshOrders()">
                    <i class="fas fa-sync-alt"></i> 刷新
                </button>
                <button class="btn btn-success" onclick="toggleAutoRefresh()">
                    <i class="fas fa-play" id="autoRefreshIcon"></i> <span id="autoRefreshText">自动刷新</span>
                </button>
            </div>
        </div>
        
        <!-- 订单列表 -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-list"></i> 实时订单列表</h5>
                    </div>
                    <div class="card-body">
                        <div id="ordersList">
                            <div class="text-center">
                                <div class="spinner-border" role="status">
                                    <span class="visually-hidden">加载中...</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 消息日志 -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5><i class="fas fa-terminal"></i> 消息日志</h5>
                        <button class="btn btn-sm btn-outline-secondary" onclick="clearLog()">清空日志</button>
                    </div>
                    <div class="card-body">
                        <div id="logContainer" class="log-container"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 通知容器 -->
    <div id="notificationContainer"></div>
    
    <!-- 订单详情模态框 -->
    <div class="modal fade" id="orderDetailModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">订单详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="orderDetailContent">
                    <!-- 订单详情内容 -->
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // WebSocket客户端
        class WebSocketClient {
            constructor() {
                this.ws = null;
                this.reconnectInterval = 5000;
                this.maxReconnectAttempts = 10;
                this.reconnectAttempts = 0;
                this.autoRefresh = false;
                this.refreshInterval = null;
                this.orders = [];
                this.stats = {
                    total: 0,
                    pending: 0,
                    confirmed: 0,
                    completed: 0
                };
                this.messageCounter = 0;
                this.connectionStartTime = null;
                
                this.init();
            }
            
            init() {
                this.setupEventListeners();
                this.loadInitialData();
            }
            
            setupEventListeners() {
                // 筛选器事件
                document.getElementById('statusFilter').addEventListener('change', () => {
                    this.filterOrders();
                });
                
                // 搜索事件
                document.getElementById('searchInput').addEventListener('input', () => {
                    this.filterOrders();
                });
            }
            
            connect() {
                const userId = document.getElementById('userId').value;
                const serverUrl = document.getElementById('serverUrl').value;
                
                if (!userId) {
                    this.showNotification('请输入用户ID', 'warning');
                    return;
                }
                
                if (this.ws) {
                    this.ws.close();
                }
                
                this.updateConnectionStatus('connecting', '连接中...');
                const url = `${serverUrl}?user_id=${userId}`;
                this.ws = new WebSocket(url);
                
                this.ws.onopen = () => {
                    this.addLog('WebSocket连接已建立', 'success');
                    this.updateConnectionStatus('connected', '已连接');
                    this.connectionStartTime = new Date();
                    document.getElementById('connectionTime').textContent = this.connectionStartTime.toLocaleTimeString();
                    document.getElementById('connectBtn').disabled = true;
                    document.getElementById('disconnectBtn').disabled = false;
                    document.getElementById('pingBtn').disabled = false;
                    this.reconnectAttempts = 0;
                };
                
                this.ws.onmessage = (event) => {
                    this.messageCounter++;
                    document.getElementById('messageCount').textContent = this.messageCounter;
                    document.getElementById('lastMessage').textContent = new Date().toLocaleTimeString();
                    
                    try {
                        const data = JSON.parse(event.data);
                        this.addLog(`收到消息: ${JSON.stringify(data, null, 2)}`, 'info');
                        this.handleMessage(data);
                    } catch (e) {
                        this.addLog(`收到消息: ${event.data}`, 'info');
                    }
                };
                
                this.ws.onclose = () => {
                    this.addLog('WebSocket连接已关闭', 'warning');
                    this.updateConnectionStatus('disconnected', '未连接');
                    document.getElementById('connectBtn').disabled = false;
                    document.getElementById('disconnectBtn').disabled = true;
                    document.getElementById('pingBtn').disabled = true;
                    this.attemptReconnect();
                };
                
                this.ws.onerror = (error) => {
                    this.addLog(`WebSocket错误: ${error}`, 'error');
                    this.updateConnectionStatus('disconnected', '连接错误');
                };
            }
            
            disconnect() {
                if (this.ws) {
                    this.ws.close();
                    this.ws = null;
                }
            }
            
            ping() {
                this.sendMessage({ type: 'ping' });
            }
            
            sendMessage(message) {
                if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                    this.ws.send(JSON.stringify(message));
                    this.addLog(`发送消息: ${JSON.stringify(message)}`, 'info');
                } else {
                    this.addLog('WebSocket未连接', 'error');
                }
            }
            
            handleMessage(message) {
                switch (message.type) {
                    case 'order_created':
                        this.handleOrderCreated(message.data);
                        break;
                    case 'order_update':
                        this.handleOrderUpdate(message.data);
                        break;
                    case 'order_status_change':
                        this.handleOrderStatusChange(message.data);
                        break;
                    case 'payment_update':
                        this.handlePaymentUpdate(message.data);
                        break;
                    case 'pong':
                        this.addLog('收到pong响应', 'success');
                        break;
                    default:
                        this.addLog(`未知消息类型: ${message.type}`, 'warning');
                }
            }
            
            handleOrderCreated(orderData) {
                this.showNotification(`新订单创建: ${orderData.order_no}`, 'info');
                this.addOrderToList(orderData);
                this.updateStats();
            }
            
            handleOrderUpdate(orderData) {
                this.showNotification(`订单更新: ${orderData.order_no}`, 'info');
                this.updateOrderInList(orderData);
                this.updateStats();
            }
            
            handleOrderStatusChange(statusData) {
                this.showNotification(`订单状态变更: ${statusData.order_no}`, 'warning');
                this.updateOrderStatus(statusData);
                this.updateStats();
            }
            
            handlePaymentUpdate(paymentData) {
                this.showNotification(`支付更新: ${paymentData.order_no}`, 'success');
                this.updateOrderPayment(paymentData);
                this.updateStats();
            }
            
            addOrderToList(orderData) {
                this.orders.unshift(orderData);
                this.renderOrders();
            }
            
            updateOrderInList(orderData) {
                const index = this.orders.findIndex(order => order.order_id === orderData.order_id);
                if (index !== -1) {
                    this.orders[index] = { ...this.orders[index], ...orderData };
                    this.renderOrders();
                }
            }
            
            updateOrderStatus(statusData) {
                const index = this.orders.findIndex(order => order.order_id === statusData.order_id);
                if (index !== -1) {
                    this.orders[index].order_status = statusData.new_status;
                    this.orders[index].updated_at = statusData.updated_at;
                    this.renderOrders();
                }
            }
            
            updateOrderPayment(paymentData) {
                const index = this.orders.findIndex(order => order.order_id === paymentData.order_id);
                if (index !== -1) {
                    this.orders[index].payment_status = paymentData.payment_status;
                    this.orders[index].paid_amount = paymentData.paid_amount;
                    this.orders[index].updated_at = paymentData.updated_at;
                    this.renderOrders();
                }
            }
            
            renderOrders() {
                const container = document.getElementById('ordersList');
                const filteredOrders = this.getFilteredOrders();
                
                if (filteredOrders.length === 0) {
                    container.innerHTML = '<div class="text-center text-muted">暂无订单数据</div>';
                    return;
                }
                
                const ordersHtml = filteredOrders.map(order => this.createOrderCard(order)).join('');
                container.innerHTML = ordersHtml;
            }
            
            createOrderCard(order) {
                const statusClass = this.getStatusClass(order.order_status);
                const paymentStatusClass = this.getPaymentStatusClass(order.payment_status);
                const statusText = this.getStatusText(order.order_status);
                const paymentStatusText = this.getPaymentStatusText(order.payment_status);
                
                return `
                    <div class="card order-card mb-3" onclick="showOrderDetail(${order.order_id})">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3">
                                    <h6 class="card-title">订单号: ${order.order_no}</h6>
                                    <p class="card-text">
                                        <small class="text-muted">创建时间: ${this.formatDate(order.created_at)}</small>
                                    </p>
                                </div>
                                <div class="col-md-2">
                                    <span class="badge status-badge ${statusClass}">${statusText}</span>
                                </div>
                                <div class="col-md-2">
                                    <span class="badge status-badge ${paymentStatusClass}">${paymentStatusText}</span>
                                </div>
                                <div class="col-md-2">
                                    <strong>金额: ¥${order.total_amount}</strong>
                                </div>
                                <div class="col-md-2">
                                    <strong>已付: ¥${order.paid_amount || 0}</strong>
                                </div>
                                <div class="col-md-1">
                                    <i class="fas fa-chevron-right text-muted"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            }
            
            getFilteredOrders() {
                const statusFilter = document.getElementById('statusFilter').value;
                const searchTerm = document.getElementById('searchInput').value.toLowerCase();
                
                return this.orders.filter(order => {
                    const matchesStatus = !statusFilter || order.order_status.toString() === statusFilter;
                    const matchesSearch = !searchTerm || 
                        order.order_no.toLowerCase().includes(searchTerm) ||
                        order.tenant_id.toLowerCase().includes(searchTerm) ||
                        order.landlord_id.toLowerCase().includes(searchTerm);
                    
                    return matchesStatus && matchesSearch;
                });
            }
            
            filterOrders() {
                this.renderOrders();
            }
            
            getStatusClass(status) {
                const statusMap = {
                    1: 'status-pending',
                    2: 'status-confirmed',
                    3: 'status-paid',
                    4: 'status-completed',
                    5: 'status-cancelled'
                };
                return statusMap[status] || 'status-pending';
            }
            
            getPaymentStatusClass(status) {
                const statusMap = {
                    1: 'payment-status-pending',
                    2: 'payment-status-paid',
                    3: 'payment-status-failed'
                };
                return statusMap[status] || 'payment-status-pending';
            }
            
            getStatusText(status) {
                const statusMap = {
                    1: '待确认',
                    2: '已确认',
                    3: '已支付',
                    4: '已完成',
                    5: '已取消'
                };
                return statusMap[status] || '未知';
            }
            
            getPaymentStatusText(status) {
                const statusMap = {
                    1: '待支付',
                    2: '已支付',
                    3: '支付失败'
                };
                return statusMap[status] || '待支付';
            }
            
            updateStats() {
                this.stats = {
                    total: this.orders.length,
                    pending: this.orders.filter(o => o.order_status === 1).length,
                    confirmed: this.orders.filter(o => o.order_status === 2).length,
                    completed: this.orders.filter(o => o.order_status === 4).length
                };
                
                document.getElementById('totalOrders').textContent = this.stats.total;
                document.getElementById('pendingOrders').textContent = this.stats.pending;
                document.getElementById('confirmedOrders').textContent = this.stats.confirmed;
                document.getElementById('completedOrders').textContent = this.stats.completed;
            }
            
            updateConnectionStatus(status, text) {
                const indicator = document.getElementById('statusIndicator');
                const statusText = document.getElementById('connectionStatusText');
                const statusElement = document.getElementById('connectionStatus');
                
                indicator.className = `status-indicator status-${status}`;
                statusText.textContent = text;
                
                if (status === 'connected') {
                    statusElement.innerHTML = '<i class="fas fa-circle text-success"></i> 已连接';
                    statusElement.className = 'alert alert-success';
                } else if (status === 'connecting') {
                    statusElement.innerHTML = '<i class="fas fa-circle text-warning"></i> 连接中...';
                    statusElement.className = 'alert alert-warning';
                } else {
                    statusElement.innerHTML = '<i class="fas fa-circle text-danger"></i> 连接断开';
                    statusElement.className = 'alert alert-danger';
                }
            }
            
            attemptReconnect() {
                if (this.reconnectAttempts < this.maxReconnectAttempts) {
                    this.reconnectAttempts++;
                    this.addLog(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`, 'warning');
                    setTimeout(() => {
                        this.connect();
                    }, this.reconnectInterval);
                } else {
                    this.showNotification('连接失败，请刷新页面重试', 'danger');
                }
            }
            
            loadInitialData() {
                // 模拟一些初始数据
                const mockOrders = [
                    {
                        order_id: 1,
                        order_no: 'ORD001',
                        order_status: 1,
                        payment_status: 1,
                        total_amount: 3000,
                        paid_amount: 0,
                        tenant_id: 'tenant001',
                        landlord_id: 'landlord001',
                        created_at: new Date().toISOString(),
                        updated_at: new Date().toISOString()
                    },
                    {
                        order_id: 2,
                        order_no: 'ORD002',
                        order_status: 2,
                        payment_status: 2,
                        total_amount: 2500,
                        paid_amount: 2500,
                        tenant_id: 'tenant002',
                        landlord_id: 'landlord002',
                        created_at: new Date(Date.now() - 3600000).toISOString(),
                        updated_at: new Date().toISOString()
                    }
                ];
                
                this.orders = mockOrders;
                this.renderOrders();
                this.updateStats();
            }
            
            showNotification(message, type = 'info') {
                const notification = document.createElement('div');
                notification.className = `alert alert-${type} alert-dismissible fade show notification`;
                notification.innerHTML = `
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                `;
                
                document.getElementById('notificationContainer').appendChild(notification);
                
                // 3秒后自动移除
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 3000);
            }
            
            formatDate(dateString) {
                const date = new Date(dateString);
                return date.toLocaleString('zh-CN');
            }
            
            addLog(message, type = 'info') {
                const logContainer = document.getElementById('logContainer');
                const timestamp = new Date().toLocaleTimeString();
                const logEntry = document.createElement('div');
                logEntry.className = `log-entry log-${type}`;
                logEntry.innerHTML = `[${timestamp}] ${message}`;
                logContainer.appendChild(logEntry);
                logContainer.scrollTop = logContainer.scrollHeight;
            }
        }
        
        // 全局函数
        function connect() {
            if (window.wsClient) {
                window.wsClient.connect();
            }
        }
        
        function disconnect() {
            if (window.wsClient) {
                window.wsClient.disconnect();
            }
        }
        
        function ping() {
            if (window.wsClient) {
                window.wsClient.ping();
            }
        }
        
        function refreshOrders() {
            if (window.wsClient) {
                window.wsClient.loadInitialData();
            }
        }
        
        function toggleAutoRefresh() {
            if (window.wsClient) {
                window.wsClient.autoRefresh = !window.wsClient.autoRefresh;
                const icon = document.getElementById('autoRefreshIcon');
                const text = document.getElementById('autoRefreshText');
                
                if (window.wsClient.autoRefresh) {
                    icon.className = 'fas fa-pause';
                    text.textContent = '停止自动刷新';
                    window.wsClient.refreshInterval = setInterval(() => {
                        refreshOrders();
                    }, 30000); // 30秒刷新一次
                } else {
                    icon.className = 'fas fa-play';
                    text.textContent = '自动刷新';
                    if (window.wsClient.refreshInterval) {
                        clearInterval(window.wsClient.refreshInterval);
                    }
                }
            }
        }
        
        function showOrderDetail(orderId) {
            if (window.wsClient) {
                const order = window.wsClient.orders.find(o => o.order_id === orderId);
                if (order) {
                    const modal = new bootstrap.Modal(document.getElementById('orderDetailModal'));
                    document.getElementById('orderDetailContent').innerHTML = `
                        <div class="row">
                            <div class="col-md-6">
                                <h6>基本信息</h6>
                                <p><strong>订单号:</strong> ${order.order_no}</p>
                                <p><strong>状态:</strong> ${window.wsClient.getStatusText(order.order_status)}</p>
                                <p><strong>支付状态:</strong> ${window.wsClient.getPaymentStatusText(order.payment_status)}</p>
                                <p><strong>总金额:</strong> ¥${order.total_amount}</p>
                                <p><strong>已付金额:</strong> ¥${order.paid_amount || 0}</p>
                            </div>
                            <div class="col-md-6">
                                <h6>时间信息</h6>
                                <p><strong>创建时间:</strong> ${window.wsClient.formatDate(order.created_at)}</p>
                                <p><strong>更新时间:</strong> ${window.wsClient.formatDate(order.updated_at)}</p>
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-12">
                                <h6>用户信息</h6>
                                <p><strong>租客ID:</strong> ${order.tenant_id}</p>
                                <p><strong>房东ID:</strong> ${order.landlord_id}</p>
                            </div>
                        </div>
                    `;
                    modal.show();
                }
            }
        }
        
        function clearLog() {
            document.getElementById('logContainer').innerHTML = '';
            if (window.wsClient) {
                window.wsClient.messageCounter = 0;
                document.getElementById('messageCount').textContent = '0';
            }
        }
        
        // 初始化WebSocket客户端
        document.addEventListener('DOMContentLoaded', function() {
            window.wsClient = new WebSocketClient();
            
            // 定期发送ping保持连接
            setInterval(() => {
                if (window.wsClient && window.wsClient.ws && window.wsClient.ws.readyState === WebSocket.OPEN) {
                    window.wsClient.ping();
                }
            }, 30000);
        });
    </script>
</body>
</html>
